<?php
namespace app\api\controller\login;

use app\api\controller\Member;
use app\common\model\CourseAttendanceModel;
use app\common\model\CourseModel;
use app\common\model\CourseStateModel;
use app\common\model\MessageModel;
use app\common\model\UserModel;
use app\common\model\UserTimesModel;
use think\db;

class Teacher extends Member
{
    /**
     * 获取教师的常规课程
     */
    public function getCourseNormal(){
        $user = $this->getMember();
        $page = $this->request->get('page', 1);
        $cate_id = $this->request->get('cate_id');
        $keyword = $this->request->get('keyword');
        $order = ['sort'=>'asc','id'=>'desc'];
        $course = CourseModel::where('status',1)
            ->where('type',1)
            ->where('teacher_id',$user['id'])
            ->where(function ($db) use ($cate_id,$keyword) {
                if (!empty($cate_id)) {
                    $db->where('cate_id', $cate_id);
                }
                if (!empty($keyword)) {
                    $db->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->order($order)
            ->page($page,20)
            ->select()
            ->toArray();
        $this->success('获取所有常规课程成功！',$course,200);
    }

    /**
     * 获取教师的兴趣课程
     */
    public function getCourseInterest(){
        $user = $this->getMember();
        $page = $this->request->get('page', 1);
        $cate_id = $this->request->get('cate_id');
        $keyword = $this->request->get('keyword');
        $order = ['sort'=>'asc','id'=>'desc'];
        $course = CourseModel::where('status',1)
            ->where('type',2)
            ->where('teacher_id',$user['id'])
            ->where(function ($db) use ($cate_id,$keyword) {
                if (!empty($cate_id)) {
                    $db->where('cate_id', $cate_id);
                }
                if (!empty($keyword)) {
                    $db->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->order($order)
            ->page($page,20)
            ->select()
            ->toArray();
        $this->success('获取所有兴趣课程成功！',$course,200);
    }

    /**
     * 获取教师的已授课课程
     */
    public function getCourseAttendance(){
        $user = $this->getMember();
        $page = $this->request->get('page', 1);
        $cate_id = $this->request->get('cate_id');
        $keyword = $this->request->get('keyword');
        $order = ['sort'=>'asc','id'=>'desc'];
        $course_ids = CourseAttendanceModel::where('teacher_id',$user['id'])
            ->field('group_concat(course_id) as course_ids')->find()['course_ids'];
        $course = CourseModel::where('status',1)
            ->where('id','in',$course_ids)
            ->where(function ($db) use ($cate_id,$keyword) {
                if (!empty($cate_id)) {
                    $db->where('cate_id', $cate_id);
                }
                if (!empty($keyword)) {
                    $db->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->order($order)
            ->page($page,20)
            ->select()
            ->toArray();
        $this->success('获取所有已授课课程成功！',$course,200);
    }

    /**
     * 获取教师的授课时长与次数
     */
    public function getTimeCount(){
        $user = $this->getMember();
        $result['count'] = CourseAttendanceModel::where('teacher_id',$user['id'])->count();
        $result['time'] =  ceil(45*$result['count']/60);
        $this->success('获取教师的授课时长与次数成功！',$result,200);
    }

    function array_sub($arr1, $arr2){
        $arr = array();
        foreach( $arr1 as $k1 => $v1 )
        {
            if( !in_array( $v1, $arr2 ) ){
                array_push( $arr, $v1 );
            }
        }
        return $arr;
    }

    /**
     * 教师点名
     */
    public function addCourseAttendance(){
        $user = $this->getMember();
        $course_id = $this->request->post('course_id');
        $all_userids = $this->request->post('all_userids');
        $all_userids = array_filter(explode(',',$all_userids));
        $in_userids = $this->request->post('in_userids');
        $in_userids = array_filter(explode(',',$in_userids));
        $away_userids = $this->array_sub($all_userids,$in_userids);

        $all_userids = implode(',',$all_userids);
        $in_userids = implode(',',$in_userids);
        $away_userids = implode(',',$away_userids);

        $time = $this->request->post('time');
        $day = date('Y-m-d');
        $attendance = CourseAttendanceModel::where('day',$day)
            ->where('course_id',$course_id)
            ->find();
        //如果在表中已经有当前日期则更新
        if(!empty($attendance)){
            CourseAttendanceModel::where('day',$day)
                ->where('course_id',$course_id)
                ->update([
                    'teacher_id'=>$user['id'],
                    'all_userids'=>$all_userids,
                    'in_userids'=>$in_userids,
                    'away_userids'=>$away_userids,
                    'time'=>$time,
                    'create_time'=>date('Y-m-d H:i:s')
                ]);
        }else{
            //在表中没有当前日期则新增
            CourseAttendanceModel::create([
                'teacher_id'=>$user['id'],
                'course_id'=>$course_id,
                'all_userids'=>$all_userids,
                'in_userids'=>$in_userids,
                'away_userids'=>$away_userids,
                'time'=>$time,
                'day'=>$day,
                'create_time'=>date('Y-m-d H:i:s')
            ]);
        }

        // 是否发送通知 1发送，2不发送
        if($this->request->post('course_id') == '2') {
            $this->success('教师点名成功！','',200);
        }

        $time = date('Y-m-d H:i:s');
        $uids = explode(',', $away_userids);
        $course_info = CourseModel::where('id',$course_id)->find();
        foreach ($uids as $uid)
        {
            $user = UserModel::find($uid);

            // 敢不来上课就告诉你爸妈！
            if(!empty($user['pid']) && $user['pid'] > 0) {
                $puser = UserModel::find($user['pid']);
                $user = $puser;
            }

            $title = '缺勤通知';
            $desc = "在{$time}的【{$course_info['name']}】课上,{$user['realname']}缺勤";
            $saveData = [
                'title' =>  $title,
                'desc' =>  $desc,
                'read_uid' =>  $uid,
            ];
            MessageModel::create($saveData);

            $data = [
                "touser"=> $user['openid'],
                "template_id"=> config('wechat.miniapp.queqin_tpl'),
                "page"=> "pages/user/user",
                "data"=> [
                    "date1"=> [
                        "value"=> $time
                    ],
                    "thing6"=> [
                        "value"=> $user['realname']
                    ],
                    "phrase7"=> [
                        "value"=> "缺勤"
                    ],
                ]
            ];
            try {
                $ret = \We::WeMiniTemplate(config('wechat.miniapp'))->send($data);
            }catch (\Exception $e){
                continue;
            }
        }

        $this->success('教师点名成功！','',200);
    }

    /**
     * 添加课程风采
     */
    public function addState(){
        $course_id = $this->request->post('course_id');
        $school_id = CourseModel::where('id',$course_id)->value('school_id');
        $images = $this->request->post('images');
        $video = $this->request->post('video');
        $desc = utf8_encode($this->request->post('desc'));
        $state = CourseStateModel::where('course_id',$course_id)
            ->find();
        //如果在表中已经有则更新
        if(!empty($state)){
            if($state['images']!=null){
                $new_images = $state['images'].','.$images;
            }else{
                $new_images = $images;
            }
            if($state['video']!=null){
                $new_video = $state['video'].','.$video;
            }else{
                $new_video = $video;
            }
            CourseStateModel::where('id',$state['id'])
                ->update([
                    'school_id'=>$school_id,
                    'course_id'=>$course_id,
                    'images'=>$new_images,
                    'video'=>$new_video,
                    'desc'=>$desc,
                    'create_time'=>date('Y-m-d H:i:s')
                ]);
        }else{
            //在表中没有则新增
            CourseStateModel::create([
                'school_id'=>$school_id,
                'course_id'=>$course_id,
                'images'=>$images,
                'video'=>$video,
                'desc'=>$desc,
                'create_time'=>date('Y-m-d H:i:s')
            ]);
        }

        $this->success('提交成功','',200);
    }

    /**
     * 获取课程风采列表
     */
    public function getStateList()
    {
//        $result = CourseStateModel::all();
        $result = CourseStateModel::where('process',2)->all();
        foreach ($result as $key => $item){
            $result[$key]['desc'] = utf8_decode($item['desc']);
        }
        if($result){
            $this->success('成功',$result,200);
        }
        $this->error('异常，请重试');
    }


//    /**
//     * 学生选课
//     */
//    public function addUserTime(){
//        $user = $this->getMember();
//        $course_id = $this->request->post('course_id');
//        $teacher_id = $this->request->post('teacher_id');
//        $time = $this->request->post('time');
//        $user_time = UserTimesModel::create([
//            'user_id'=>$user['id'],
//            'course_id'=>$course_id,
//            'teacher_id'=>$teacher_id,
//            'time'=>$time,
//            'create_time'=>date('Y-m-d H:i:s')
//        ]);
//        CourseModel::where('id',$course_id)->setInc('sign_count');
//        if(!empty($user_time)){
//            $this->success('学生选课成功！',$user_time,200);
//        }else{
//            $this->error('学生选课失败！','',401);
//        }
//    }
}